﻿using System;
using System.Linq;
using System.Web.Security;

namespace pbvs.Admin
{
    public class PbvsRoleProvider : RoleProvider
    {
        private readonly PbvsUserRepository _repository;
        
        public PbvsRoleProvider()
        {
            this._repository = new PbvsUserRepository();
        }

        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            foreach (string username in usernames)
            {
                foreach (string roleName in roleNames)
                {
                    if (RoleExists(roleName))
                    {
                        _repository.AddRoleToUser(username, roleName);
                    }
                }
            }
            _repository.Save();
        }

        public override string ApplicationName
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public override void CreateRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            throw new NotImplementedException();
        }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            return
                _repository.GetRole(roleName)
                           .Logins.Where(l => l.Email.ToLower() == usernameToMatch.ToLower())
                           .Select(l => l.Email)
                           .ToArray();
        }

        public override string[] GetAllRoles()
        {
            return _repository.GetAllRoles().Select(r => r.Name).ToArray();
        }

        public override string[] GetRolesForUser(string username)
        {
            return _repository.GetAllRolesForUser(username).Select(r => r.Name).ToArray();
        }

        public override string[] GetUsersInRole(string roleName)
        {
            return _repository.GetRole(roleName).Logins.Select(l => l.Email).ToArray();
        }

        public override bool IsUserInRole(string username, string roleName)
        {
            PbvsUser user = _repository.GetUser(username);
            if (user != null)
            {
                return user.Login.Roles.Any(r => r.Name.ToLower() == roleName.ToLower());
            }
            return false;
        }

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override bool RoleExists(string roleName)
        {
            return _repository.RoleExists(roleName);
        }
    }
}